/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.api.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chengcang.api.modules.sys.dao.SysDictDataDao;
import com.chengcang.api.modules.sys.dao.SysDictTypeDao;
import com.chengcang.api.modules.sys.dto.SysDictDataDTO;
import com.chengcang.api.modules.sys.entity.DictData;
import com.chengcang.api.modules.sys.entity.DictType;
import com.chengcang.api.modules.sys.entity.SysDictDataEntity;
import com.chengcang.api.modules.sys.service.SysDictDataService;
import com.chengcang.api.modules.sys.service.SysDictTypeService;
import com.chengcang.common.constant.RedisConstant;
import com.chengcang.common.enums.DataTypeEnum;
import com.chengcang.common.page.PageData;
import com.chengcang.common.redis.RedisUtils;
import com.chengcang.common.service.impl.BaseServiceImpl;
import com.chengcang.common.utils.ConvertUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 字典类型
 *
 * @author zhanli
 */
@Service
@RequiredArgsConstructor
public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysDictDataEntity> implements SysDictDataService {

    private final SysDictTypeDao sysDictTypeDao;
    private final RedisUtils redisUtils;
    private final SysDictTypeService sysDictTypeService;

    @Override
    public PageData<SysDictDataDTO> page(Map<String, Object> params) {
        IPage<SysDictDataEntity> page = baseDao.selectPage(
                getPage(params, "sort", true),
                getWrapper(params)
        );

        return getPageData(page, SysDictDataDTO.class);
    }

    private QueryWrapper<SysDictDataEntity> getWrapper(Map<String, Object> params) {
        String dictTypeId = (String) params.get("dictTypeId");
        String dictLabel = (String) params.get("dictLabel");
        String dictValue = (String) params.get("dictValue");

        QueryWrapper<SysDictDataEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_type_id", dictTypeId);
        wrapper.like(StringUtils.isNotBlank(dictLabel), "dict_label", dictLabel);
        wrapper.like(StringUtils.isNotBlank(dictValue), "dict_value", dictValue);

        return wrapper;
    }

    @Override
    public SysDictDataDTO get(Long id) {
        SysDictDataEntity entity = baseDao.selectById(id);

        return ConvertUtils.sourceToTarget(entity, SysDictDataDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysDictDataDTO dto) {
        SysDictDataEntity entity = ConvertUtils.sourceToTarget(dto, SysDictDataEntity.class);

        insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDictDataDTO dto) {
        SysDictDataEntity entity = ConvertUtils.sourceToTarget(dto, SysDictDataEntity.class);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        //删除 selectByTypeAndKey
        deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public String getValue(DataTypeEnum type, String dictValue) {
        if (StringUtils.isBlank(dictValue)) {
            return null;
        }
        Object obj = redisUtils.hGet(RedisConstant.SYS_DICT_DATA_API, type.getKey());
        if (obj != null && obj instanceof List) {
            List<DictData> list = (List<DictData>) obj;
            return getDetail(list, dictValue);
        }
        List<DictType> dictTypes = sysDictTypeService.getAllList();
        if (CollectionUtils.isNotEmpty(dictTypes)) {
            Map<String, Object> listMap = dictTypes.stream().collect(Collectors.toMap(DictType::getDictType, DictType::getDataList));
            redisUtils.hMSet(RedisConstant.SYS_DICT_DATA_API, listMap);
            return getDetail((List<DictData>) listMap.get(type.getKey()), dictValue);
        }

        return null;
    }

    @Override
    public List<String> getListingValue(DataTypeEnum type, String... dictValue) {
        List<String> list = new ArrayList<>();
        for (String key : dictValue) {
            String value = getValue(type, key);
            if (StringUtils.isNotBlank(value)) {
                list.add(value);
            }
        }
        return list;
    }

    @Override
    public String getJoiningValue(DataTypeEnum type, String... dictValue) {
        return String.join(",", getListingValue(type, dictValue));
    }

    public Map<String, String> getDataByField(String fieldName) {
        Map<String, String> resultMap = new HashMap<>(1);
        //查询单个数据字典key
        if (StringUtils.isNotBlank(fieldName)) {
            Object fieldObj = redisUtils.hGet(RedisConstant.SYS_DICT_DATA, humpToLine(fieldName));
            if (fieldObj != null) {
                List<DictData> list = (List<DictData>) fieldObj;
                for (DictData dictData : list) {
                    resultMap.put(dictData.getDictValue(), dictData.getDictLabel());
                }
                return resultMap;
            }
        }
        //resultMap根据dataSort进行排序
        return resultMap;
    }


    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 驼峰转下划线,效率比上面高
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    private String getDetail(List<DictData> list, String dictValue) {
        return list.stream().filter(o -> Objects.equals(dictValue, o.getDictValue())).findFirst().map(DictData::getDictLabel).orElse(null);
    }




}